package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.BusException;
import com.atguigu.lease.common.jwtutil.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;

    private static final String KEY_PREFIX = RedisConstant.APP_LOGIN_PREFIX;

    public void getCode(String phone) {
//        第一步先对手机进行校验
        if(!StringUtils.hasText(phone)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

//        发验证码的时候要知道验证码存储的位置
        String redisCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if(redisCode != null){
            Long expire = stringRedisTemplate.getExpire(KEY_PREFIX + phone, TimeUnit.SECONDS);
//            使用当年存储的时候设置的过期时间减去当前时间的剩余时间（expire）如果是小于60秒，则不能再发验证码
//            如果没有，后面就可以发
            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new BusException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
//      发短信 = phone + code  (做一个工具方法专门生成验证码)  把手机和验证码传递给专门发短信的工具方法
        String code = createCode(6);
//      发送短信
        sendCode(phone,code);
//        存储验证码到redis
        stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if (!StringUtils.hasText(phone)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        String redisCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (redisCode == null){
            throw new BusException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!code.equals(redisCode)){
            throw new BusException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setNickname("用户" + phone.substring(phone.length() - 7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }

        if (userInfo.getStatus() == BaseStatus.DISABLE){
            throw new BusException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());

        return token;
    }


    public String createCode(Integer length){
        StringBuilder sb = new StringBuilder();
        Random rendom = new Random();
        for (int i = 0; i < length; i++){
           sb.append(rendom.nextInt(10));
        }
        return sb.toString();

    }
    public void sendCode(String phone, String code){
//        专门负责发 给哪发和发什么你需要传
//     第一步：对接阿里云短信服务
//     第二步：通过阿里云的api代码进行改造
//        1、创建一个Client对象放入ioc
//        2、在发短信的位置拿到Client对象进行发短信

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":"+ "\"" + code + "\"" + "}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception error) {
            throw new BusException(ResultCodeEnum.SERVICE_ERROR);
        }

    }


}
